<template>
	<el-dialog :title="titleMap[mode]+'【'+total_price+'】'" v-model="visible" width="50vw" destroy-on-close @closed="$emit('closed')"
             :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true">
		<el-form ref="dialogForm" label-width="110px" label-position="right">
			<sc-form-table ref="table" v-model="stages_all" placeholder="暂无数据" height="600" hideAdd hideDelete>
				<el-table-column prop="type" label="期别" align="center" width="100">
					<template #default="scope">
						第{{ scope.row.stages_number }}期
					</template>
				</el-table-column>
				<el-table-column label="付款百分比" prop="collect_rate" align="center">
					<template #default="scope">
						<el-input-number type="number" v-model="scope.row.collect_rate" placeholder="付款百分比" :min="1"
										 @change="rateChange(scope.row,scope.$index)" controls-position="right">
							<template #suffix>
								<span>%</span>
							</template>
						</el-input-number>
					</template>
				</el-table-column>
				<el-table-column label="付款金额" prop="money" align="center">
					<template #default="scope">
						<el-input-number type="number" v-model="scope.row.money" placeholder="付款金额" :min="1"
										 @change="priceChange(scope.row,scope.$index)" controls-position="right"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column label="款项日期" prop="collect_date" align="center">
					<template #default="scope">
						<el-date-picker v-model="scope.row.collect_date" type="date" placeholder="请选择日期"
										:value-format="'YYYY-MM-DD'" style="width:100%" />
					</template>
				</el-table-column>
				<el-table-column label="备注" prop="remark" align="center">
					<template #default="scope">
						<el-input v-model="scope.row.remark" placeholder="备注"></el-input>
					</template>
				</el-table-column>
			</sc-form-table>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
export default {
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '设置分期付款',
				edit: '设置分期付款',
				show: '设置分期付款'
			},
			visible: false,
			isSaveing: false,
			total_price:0,
			stages_all:[],
			maxStages: 12,  // 最多12期
		}
	},
	mounted() {

	},
	methods: {
		/**付款百分比输入事件*/
		rateChange(row,index) {
			row.money = (Number(this.total_price) * (Number(row.collect_rate))/100)
			row.money = row.money.toFixed(2)
			this.getLastRow(row,index)
		},
		/**付款金额输入事件*/
		priceChange(row,index) {
			row.collect_rate = (Number(row.money)/Number(this.total_price))*100
			row.collect_rate = row.collect_rate.toFixed(2)
			this.getLastRow(row,index)
		},
		/**修改阶段金额或百分比后自动增加下一个阶段*/
		getLastRow(row,index) {
			console.log('row',row,index)
			// 删除修改当前行之后的数据
			if(index + 1 < this.stages_all.length) {
				this.stages_all.splice(index+1)
			}
			// 更新第一期百分比变化后，自动更新后续阶段
			let totalMoney = 0;
			for (let i = 0; i <= index; i++) {
				totalMoney += Number(this.stages_all[i].money);
			}
			// 计算除当前行之前的合计金额
			let firstMoney = 0;
			for (let i = 0; i < index; i++) {
				firstMoney += Number(this.stages_all[i].money);
			}
			console.log('totalMoney',totalMoney)
			// 如果百分比合计已达到100，删除超出阶段
			if (totalMoney < this.total_price) {
				console.log('index >= (this.maxStages-1)',index ,this.maxStages-1)
				if(index >= (this.maxStages-1)) {
					row.money = Number(this.total_price) - Number(firstMoney)
					row.money = row.money.toFixed(2)
					row.collect_rate = (Number(row.money)/Number(this.total_price))*100
					row.collect_rate = row.collect_rate.toFixed(2)
				} else {
					this.addNextStage()
				}
			} else if (totalMoney > this.total_price) {
				row.money = Number(this.total_price) - Number(firstMoney)
				row.money = row.money.toFixed(2)
				row.collect_rate = (Number(row.money)/Number(this.total_price))*100
				row.collect_rate = row.collect_rate.toFixed(2)
			}
		},
		/**添加下一个阶段*/
		addNextStage() {
			let nextStageNumber = this.stages_all.length + 1;
			let totalMoney = 0 // 计算当前所有阶段的金额总和
			this.stages_all.map(item=>{
				totalMoney+=Number(item.money)
			})
			let nextMoney = this.total_price - totalMoney;  // 剩余的金额
			if (nextMoney > 0) {
				let prevDate = this.moment(this.stages_all[this.stages_all.length - 1].collect_date);
				let nextDate = prevDate.add(1, 'month');  // 下一期日期（假设是按月递增）
				let collect_date = nextDate.format('YYYY-MM-DD');

				let nextStage = {
					stages_number: nextStageNumber,
					collect_rate: ((Number(nextMoney)/Number(this.total_price))*100).toFixed(2),
					money: nextMoney,  // 计算新一期的金额
					collect_date: collect_date,
					remark: "",
				};
				this.stages_all.push(nextStage);
			}
		},
		//表单注入数据
		setData(data) {
            this.total_price = data.total_amount
			let stages_all = data.stages_all
			if(stages_all.length<=0) {
				let firstStage = {
					stages_number: 1,
					collect_rate: 100,
					money: data.total_amount,
					collect_date: this.moment().format('YYYY-MM-DD'),
					remark: ""
				}
				this.stages_all.push(firstStage)
			} else {
				this.stages_all = [...stages_all]; // 保证数据正确更新
			}
		},
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit() {
			this.$emit('success', this.stages_all)
			this.visible = false;
		},
	}
}
</script>

<style></style>
